var https = require('https');
var Promise = require('promise');
var jsSHA = require('jssha');
var logger = require("log4js").getLogger('wechatRest.js');

var config = require('../../config');
var fansModel = require('../wechat/model/Fans');


var wechatRest = {};

// 获取access_token信息
wechatRest.getAccessToken = function(appId, appSecret) {
  return new Promise(function(fulfill, reject){
	  var url = config.wechat.accessTokenUrl;
	  url = url.replace('{appid}', appId);
	  url = url.replace('{appsecret}', appSecret);
	  https.get(url, function(res) {
	    res.on('data', function(d) {
	      logger.debug('19, getAccessToken data : ' + d);      
	      d = JSON.parse(d);
	      if (d && d.errcode) {
	        logger.error('21,getAccessToken error : ' + d.errmsg);
	        reject(d.errmsg);
	      }
	      if (d) {
	    	  fulfill(d.access_token);
	      }
	    });
	  }).on('error', function(e) {
	    logger.error('30,getAccessToken error : ' + e.message);
	    reject(e.message);
	  });
  });
  
};


//获取jsapi_ticket
wechatRest.getJsTicket = function(accessToken){
	return new Promise(function(fulfill,reject){
		var url = config.wechat.jsTicketUrl;
		  url = url.replace('{accesstoken}', accessToken);
		  https.get(url, function(res) {
		    res.on('data', function(d) {
		      logger.debug('43, getJsTicket data : ' + d);      
		      d = JSON.parse(d);
		      if (d &&(d.errcode==0)) {
		    	  fulfill(d.ticket);
		      }else{
		    	 logger.error('48,getJsTicket error : ' + d.errmsg);
		    	 reject(d.errmsg);
		      }
		    });
		  }).on('error', function(e) {
		    logger.error('28,getAccessToken error : ' + e.message);
		    reject(e.message);
		  })
	});
};

//
//// 根据openid获取用户信息
//wechatRest.getFans = function(openId, accessToken, callback) {
//  var url = config.wechat.fansUrl;
//  url = url.replace('{openid}', openId);
//  url = url.replace('{access_token}', accessToken);
//  https.get(url, function(res) {
//    res.on('data', function(d) {
//      logger.debug('40, getFans data : ' + d);
//      d = JSON.parse(d);
//      if (d && d.errcode) {
//    	  logger.debug('43, errcode : ' + d.errcode);
//          callback(undefined);
//      }
//      if (d && callback) {
//        callback(fansModel.wechatConvertModel(d));
//      }
//    });
//  }).on('error', function(e) {
//	  logger.debug('45, getFans error : ' + e.message);
//	  callback(undefined);
//  });
//};

// 根据openid获取用户信息
wechatRest.getFans = function(openId, accessToken) {
    return new Promise(function(fulfill, reject){
        var url = config.wechat.fansUrl;
        url = url.replace('{openid}', openId);
        url = url.replace('{access_token}', accessToken);
        https.get(url, function(res) {
            res.on('data', function(d) {
                d = JSON.parse(d);
                if (d && d.errcode) {
                    logger.error('getFans error : ' + d.errmsg);
                    reject(d.errmsg);
                }
                if (d) {
                    fulfill(fansModel.wechatConvertModel(d));
                }
            });
        }).on('error', function(e) {
            logger.error('getFans error : ' + e.message);
            reject(e.message);
        });
    });
};

// 根据openid获取用户信息
wechatRest.getSnsFans = function(openId, accessToken) {
	return new Promise(function(fulfill, reject){
		var url = config.wechat.snsFansUrl;
		  url = url.replace('{openid}', openId);
		  url = url.replace('{access_token}', accessToken);
		  https.get(url, function(res) {
		    res.on('data', function(d) {
		      d = JSON.parse(d);
		      if (d && d.errcode) {
		        logger.error('getsnsFans error : ' + d.errcode + " | " + d.errmsg);
		         reject(d.errmsg);
		      }
		      if (d) {
		    	 fulfill(fansModel.wechatConvertModel(d));
		      }
		    });
		  }).on('error', function(e) {
		    logger.error('getsnsFans error : ' + e.message);
		    reject(e.message);
		  });
	});
};

// 获取授权跳转链接
wechatRest.getRedirectUrls = function(account,redirectUri, scope, state) {
  var url = config.wechat.authUrl;
  var domain = account.domain||config.main.url;
  url = url.replace('{appid}', account.appId);
  url = url.replace('{redirect_uri}', encodeURIComponent(domain+redirectUri));
  url = url.replace('{state}', encodeURIComponent(state));
  url = url.replace('{scope}', scope);
  return url;
};

// 根据code 获取授权信息
wechatRest.auth = function(appId, appSecret, code) {
  return new Promise(function(fulfill, reject){
	  var url = config.wechat.auth2TokenUrl;
	  url = url.replace('{appid}', appId);
	  url = url.replace('{appsecret}', appSecret);
	  url = url.replace('{code}', code);
	  https.get(url, function(res) {
	    res.on('data', function(d) {
	      logger.debug('126, auth data : ' + d);      
	      d = JSON.parse(d);
	      if (d && d.errcode) {
	        logger.error('157,auth error :'  + d.errcode + " | " + d.errmsg);
	        reject(d.errmsg);
	      }
	      if (d){
			  fulfill(d);
		  }
	    });
	  }).on('error', function(e) {
	    logger.error('136,auth error : ' + e.message);
	    reject(e.message);
	  })
  });
};

//校验授权信息
wechatRest.verifyAuth = function(req, res, next) {
	var fans = req.session.fans;
	if (!fans) {	
		logger.debug('verify auth now...');
		// 如果没有授权
		logger.debug('req.originalUrl : ' + req.originalUrl);	
		req.session.backUrl = req.originalUrl;
		res.redirect('/wechat/auth');
	} else {
		next();
	}
	// });
};


//js-sdk签名
function _sign(jsTicket, url){
	var ret = {
		jsapi_ticket : jsTicket,
		nonceStr : Math.random().toString(36).substr(2, 15),
		timestamp : parseInt(new Date().getTime() / 1000) + '',
		url : url
	};
	var keys = Object.keys(ret);
	keys = keys.sort();
	var newArgs = {};
	keys.forEach(function(key) {
		newArgs[key.toLowerCase()] = ret[key];
	});

	var string = '';
	for ( var k in newArgs) {
		string += '&' + k + '=' + newArgs[k];
	}
	string = string.substr(1);
	var shaObj = new jsSHA(string, 'TEXT');
	ret.signature = shaObj.getHash('SHA-1', 'HEX');

	jsSHA = require('jssha');
	shaObj = new jsSHA(string, 'TEXT');
	ret.signature = shaObj.getHash('SHA-1', 'HEX');

	return ret;
}
wechatRest.sign = function(jsTicket, url) {
	return _sign(jsTicket,url);
};

wechatRest.wechatSign = function(req){
	var url = req.protocol+"://" + req.hostname + req.originalUrl;
	var ret = _sign(req.session.account.jsTicket, url);
	var wechatSign = {
		appId: req.session.account.appId, // 微信签名参数
		timestamp: ret.timestamp,
		nonceStr: ret.nonceStr,
		signature: ret.signature
	};
	return wechatSign;
};


module.exports = wechatRest;